<script setup>
import { computed } from 'vue'
import { useAuthStore } from '../store/auth'

const props = defineProps({
  // 需要的权限
  permission: {
    type: [String, Array],
    default: null
  },
  // 需要的角色
  role: {
    type: [String, Array],
    default: null
  },
  // 权限检查模式：all(与) 或 any(或)
  mode: {
    type: String,
    default: 'any',
    validator: (value) => ['all', 'any'].includes(value)
  },
  // 是否显示无权限时的占位内容
  showFallback: {
    type: Boolean,
    default: false
  }
})

const authStore = useAuthStore()

// 检查权限
const hasPermission = computed(() => {
  if (!props.permission) return true
  
  if (Array.isArray(props.permission)) {
    if (props.mode === 'all') {
      return props.permission.every(p => authStore.hasPermission(p))
    } else {
      return props.permission.some(p => authStore.hasPermission(p))
    }
  }
  
  return authStore.hasPermission(props.permission)
})

// 检查角色
const hasRole = computed(() => {
  if (!props.role) return true
  
  if (Array.isArray(props.role)) {
    return props.role.includes(authStore.userRole)
  }
  
  return authStore.hasRole(props.role)
})

// 是否有访问权限
const hasAccess = computed(() => {
  return hasPermission.value && hasRole.value
})
</script>

<template>
  <div v-if="hasAccess">
    <slot />
  </div>
  <div v-else-if="showFallback" class="permission-fallback">
    <slot name="fallback">
      <div class="no-permission">
        <el-icon><Lock /></el-icon>
        <span>暂无权限访问</span>
      </div>
    </slot>
  </div>
</template>

<style scoped>
.permission-fallback {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #999;
}

.no-permission {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.no-permission .el-icon {
  font-size: 24px;
}
</style>